<?php 

require_once("config.php"); 

$tpl = new Smarty();
$tpl->compile_dir = "$document_root/templates/cache";
$tpl->template_dir = "$document_root/templates";
$tpl->left_delimiter = "{%";
$tpl->right_delimiter = "%}";
$tpl->assign("logged", $_SESSION['authenticated']);

if ($_SESSION['authenticated'] == 1) {
	$ff = new friendfeed($key, $secret, 
			    array(  'oauth_token' => $_SESSION['oa']['oauth_token'], 
				    'oauth_token_secret' => $_SESSION['oa']['oauth_token_secret']
			    )
			);
	$username = $_SESSION["oa"]["username"];

	$u = $ff->fetch_feed_info($username);
	$user = array("id"=>$u->id, "name"=>$u->name,"description"=>$u->description);
	$tpl->assign("user", $user);
}


switch ($_GET["action"]) 
{
    case "switcher":
	$operation = (boolean) ($_POST["op"] != "false");

	list($feed_id, $list_id) = split(":", $_POST["id"]);

	if ($operation) {
		$ff->subscribe("$feed_id", array("list"=>"$list_id"));
	}
	else {
		$ff->unsubscribe("$feed_id", array("list"=>"$list_id"));

	}
	break;

default:

    case "list":
if ($_SESSION['authenticated'] == 1) {

foreach($u->subscriptions as $item) {
	$list[$item->type][] = $item; 
}

$feed = $ff->fetch_feed_list();

foreach($feed->sections[0]->feeds as $item) {
	list($type) = split("/", $item->id);
	if (in_array($type, array("list", "home"))) {
		$userlist[$item->id]["id"] = $item->id;
		$userlist[$item->id]["name"] = $item->name;
		$info = $ff->fetch_feed_info($item->id);
		foreach($info->feeds as $fit) {
			$userlist[$item->id]["feeds"][$fit->id] = true;
		}
	}
}

$type = ($_REQUEST["type"] == "g") ? "group" : "user";
$clist = $list[$type];

$tpl->assign("type", $_REQUEST["type"]);
$tpl->assign("list", $clist);
$tpl->assign("ulist", $userlist);
$place_holder = $tpl->fetch("list_detail.tpl");
}		
        break;
    case "authentication":
    {
        $ff = new FriendFeed($key, $secret);
        $s = $_GET['oauth_token'];

        try {
            $p = $ff->fetch_oauth_access_token( array('oauth_token'=>$s, 'oauth_token_secret'=>$_SESSION['oauth_token_secret'] ) );
            $_SESSION['authenticated'] = 1;
            $_SESSION['oa'] = $p;
 
            header('Location: ?action=list');
            die();
        } 
        catch (Exception $e) {
            $place_holder = '<h2>Oops, sorry an error occured</h2>
   				<a href="login.php"><img src="images/sign-in-with-friendfeed.png" border="0" /></a>';

        }
    }
    break;
    }

$tpl->assign("place_holder", $place_holder);
$tpl->display("master.tpl");

